﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Chefbook.HelperMethods
{
    /// <summary>
    /// An IEqualityComparer that takes a Func that can passed as a lambda expression 
    /// for equality comparison and optionally takes a hash Func
    /// </summary>
    /// <typeparam name="T">The type being compared</typeparam>
    public class LambdaComparer<T> : IEqualityComparer<T>
    {
        private readonly Func<T, T, bool> _lambdaComparer;
        private readonly Func<T, int> _lambdaHash;

        /// <summary>
        /// Creates a new IEqualityComparer that takes a Func so we can pass in an arbitrary lambda expression
        /// </summary>
        /// <param name="lambdaComparer">The function for comparing equality</param>
        public LambdaComparer(Func<T, T, bool> lambdaComparer) :
            this(lambdaComparer, o => o.GetHashCode())
        {
        }

        /// <summary>
        /// Creates a new IEqualityComparer that takes a Func so we can pass in an arbitrary lambda expression
        /// </summary>
        /// <param name="lambdaComparer">The function for comparing equality</param>
        /// <param name="lambdaHash">The function for generating a hash code</param>
        public LambdaComparer(Func<T, T, bool> lambdaComparer, Func<T, int> lambdaHash)
        {
            if (lambdaComparer == null)
                throw new ArgumentNullException("lambdaComparer");
            if (lambdaHash == null)
                throw new ArgumentNullException("lambdaHash");

            _lambdaComparer = lambdaComparer;
            _lambdaHash = lambdaHash;
        }

        /// <summary>
        /// Returns whether x equals y using this comparer function
        /// </summary>
        /// <param name="x">The first parameter</param>
        /// <param name="y">The second parameter</param>
        /// <returns>True if x equals y</returns>
        public bool Equals(T x, T y)
        {
            return _lambdaComparer(x, y);
        }

        /// <summary>
        /// Gets the hashcode of the object
        /// </summary>
        /// <param name="obj">The object to find the hash code of</param>
        /// <returns>The hash code</returns>
        public int GetHashCode(T obj)
        {
            return _lambdaHash(obj);
        }
    }

}